package com.example.rabbit;

import com.example.async.*;
import com.example.bean.Verdict;
import com.example.toolkit.ConvertUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.Future;

@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "exam.request", durable = "true"),
        exchange = @Exchange(value = "exam_request"),
        key = "exam.request"))
public class Receiver {
    @Autowired
    private Sender sender;
    @Autowired
    private TaskPerson taskPerson;

    private Logger logger = LoggerFactory.getLogger(Receiver.class);

    @RabbitHandler
    public void process(@Payload Object context) {
        ConvertUtil convertUtil = new ConvertUtil();
        byte[] inputStream = ((Message) context).getBody();
        String inputString = convertUtil.UTF8ToString(inputStream);

        Gson gson = new Gson();
        Map<String, String> params = gson.fromJson(inputString, new TypeToken<Map<String, String>>() {}.getType());

        String i_sn = params.get("sn");//唯一编码
        String i_id_num = params.get("id_num");

        Boolean B1 = false;

        try {
            Future<Boolean> task_B1 = taskPerson.doTaskQuery(i_id_num);

            while (true) {
                if (task_B1.isDone()) {
                    break;
                }
            }

            B1 = task_B1.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("任务执行完成。" + "查询：" + B1);
        Verdict v = new Verdict(i_sn);
        v.setStatus_code(0);
        v.setStatus_info("正常");

        //返回gson send
        sender.send(gson.toJson(v));
    }
}
